package clustersimulator;

import java.io.Reader;

import net.sf.javaml.core.Dataset;
import net.sf.javaml.core.DefaultDataset;
import net.sf.javaml.core.DenseInstance;
import be.abeel.io.LineIterator;

public class ClusterStreamHandler {

	public static Dataset[] load(Reader in, int classIndex, String separator) {

	        LineIterator it = new LineIterator(in);
	        it.setSkipBlanks(true);
	        it.setSkipComments(true);

		int cluster = 0;

		// Count the clusters in the file
		for (String line : it) {
			if (line == "********************************")
				cluster++;
		}
		it.close();
		it = new LineIterator(in);
		it.setSkipBlanks(true);
		it.setSkipComments(true);
		Dataset[] out = new Dataset[cluster];
		
		for (int i=0; i < out.length; i++)
			out[i] = new DefaultDataset();

		cluster = 0;
	        for (String line : it) {
	        	if (line == "********************************") {
	        		cluster++;
	        	}
	        	else {
	        		String[] arr = line.split(separator);
	        		double[] values;
	        		if (classIndex == -1)
	        			values = new double[arr.length];
	        		else
	        			values = new double[arr.length - 1];
	        		String classValue = null;
	        		for (int i = 0; i < arr.length; i++) {
	        			if (i == classIndex) {
	        				classValue = arr[i];
	        			} else {
	        				double val;
	        				try {
	        					val = Double.parseDouble(arr[i]);
	        				} catch (NumberFormatException e) {
	        					val = Double.NaN;
	        				}
	        				if (classIndex != -1 && i > classIndex)
	        					values[i - 1] = val;
	        				else
	        					values[i] = val;
	        			}
	        		}
	        		out[cluster].add(new DenseInstance(values, classValue));
	        	}
	        }
	        it.close();
	        return out;
	}

	public static Dataset[] load(Reader in, int classIndex) {
		return load(in, classIndex, ",");
	}

	public static Dataset[] load(Reader in) {
		return load(in, 0, ",");
	}
}
